package com.topscomm.mis.cbb.pm.service.chain.handler;

import com.topscomm.mis.cbb.pm.api.ITaskService;
import com.topscomm.mis.cbb.pm.base.pojo.CbbPmTaskEntity;
import com.topscomm.mis.cbb.pm.base.service.ICbbPmTaskService;
import com.topscomm.mis.cbb.pm.base.service.impl.CbbPmTaskService;
import com.topscomm.mis.cbb.pm.service.chain.TaskCompleteHandler;
import com.topscomm.mis.cbb.pm.service.impl.TaskService;
import com.topscomm.mis.cbb.pm.util.PmSystemConst;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import java.util.*;

/**
 * @description: 责任链竞争任务处理
 * @author: wangxinhua
 * @date: 2023/6/16 10:07
 * @modify:
 */
@Scope(value = "singleton")
public class CompetitionHandler extends TaskCompleteHandler {
    @Override
    public void completeTask(Map<String, Object> taskInfo) {
        CbbPmTaskService cbbPmTaskService =  (CbbPmTaskService) SpringUtil.getBean("cbbPmTaskService");
        TaskService taskService =  (TaskService) SpringUtil.getBean("taskService");
        if (PmSystemConst.TaskRelation.COMPETITION == ConvertUtil.convertToInt(taskInfo.get(CbbPmTaskEntity.FieldRelation))){
            // 处理竞争类型任务
            //更新任务状态
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put(CbbPmTaskEntity.FieldStatus, PmSystemConst.TaskStatus.COMPLETE);
            updateMap.put(CbbPmTaskEntity.FieldRealendtime, new Date());
            //完成同级的竞争节点任务
            List<Integer> notCompleteStatus = taskService.getNotCompleteStatus();
            StringBufferProxy updateSql = new StringBufferProxy();
            updateSql.appendSingle(" {0}='{1}' ", CbbPmTaskEntity.FieldParentcode, taskInfo.get(CbbPmTaskEntity.FieldParentcode));
            updateSql.appendSingle(" and {0}='{1}' ", CbbPmTaskEntity.FieldCurrently, PmSystemConst.CboYesNo.YES);
            updateSql.appendSingle(" and {0} in ({1}) ", CbbPmTaskEntity.FieldStatus, StringUtils.join(notCompleteStatus, ","));
            updateSql.appendSingle(" and {0} in ({1}) ", CbbPmTaskEntity.FieldRelation, PmSystemConst.TaskRelation.COMPETITION);
            cbbPmTaskService.updateByWhere(updateMap, updateSql.toString());
        }else {
            this.getNextHandler().completeTask(taskInfo);
        }
    }
}
